package net.neimeng.luculent.coremodel.datamodel.http;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


import net.neimeng.luculent.coremodel.BuildConfig;
import net.neimeng.luculent.coremodel.utils.Logger;
import net.neimeng.luculent.coremodel.utils.SPConstant;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by jaycee on 2017/6/23.
 */
public class RetrofitUtils {


    private static String TAG = "RetrofitUtils";

    private static final String BASE_URL = BuildConfig.BASE_URL;

    private static final long TIMEOUT = 30;

    // Retrofit是基于OkHttpClient的，可以创建一个OkHttpClient进行一些配置
    private static OkHttpClient httpClient = new OkHttpClient.Builder()
            // 添加通用的Header
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request.Builder builder = chain.request().newBuilder();
                    builder.addHeader("x-access-token", SPUtils.getInstance().getString(SPConstant.HTTP_TOKEN, ""));
                    builder.addHeader("api-version", "1");
                    return chain.proceed(builder.build());
                }
            })
            /*
            这里可以添加一个HttpLoggingInterceptor，因为Retrofit封装好了从Http请求到解析，
            出了bug很难找出来问题，添加HttpLoggingInterceptor拦截器方便调试接口
             */
            .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Logger.i(TAG, message);
                }
            })
            .setLevel(HttpLoggingInterceptor.Level.BODY))
            .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(TIMEOUT, TimeUnit.SECONDS)
            .build();


    private static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            // 添加Gson转换器
            .addConverterFactory(GsonConverterFactory.create(buildGson()))
            // 添加Retrofit到RxJava的转换器
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(httpClient)
            .build();


    private static Map<Class, Object> services = new HashMap<Class, Object>();

    public static <T> T getService(Class<T> t) {
        Object service = services.get(t);
        if (service == null) {
            service = retrofit.create(t);
            services.put(t, service);
        }
        return (T) service;
    }

    private static Gson buildGson() {
        return new GsonBuilder()
                .serializeNulls()
                .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                .setPrettyPrinting() //对json结果格式化.
                // 此处可以添加Gson 自定义TypeAdapter
                //.registerTypeAdapter(User.class, new UserTypeAdapter())
                .create();
    }
}
